﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Runtime.InteropServices;
using Word;
using System.IO;
using System.Data;
using System.Timers;
using System.Collections;
using System.Xml;

namespace XMLToWordLib
{
    public class Class_WordControler
    {


        [DllImport("user32.dll")]
        public static extern int FindWindow(string strclassName, string strWindowName);


        public delegate void M_GetRelativeInfo(object sender, EventArgs_数据类 e);

        public event M_GetRelativeInfo M_获取相关推送;

        /// <summary>
        /// Word文档类

        /// </summary>
        public Word.Document document;
        private string filename = "";

        /// <summary>
        /// 当前活动word对象
        /// </summary>
        public static Word.ApplicationClass wd = null;

        /// <summary>
        /// word应用的句柄

        /// </summary>
        public static int wordWnd = 0;

        private Timer time1 = new Timer(2000);
        private string M_oldtext = "";
        private string M_oldSelection = "";
        public Class_WordControler()
        {
            //time1.Enabled = true;
            time1.Elapsed += new ElapsedEventHandler(time1_Elapsed);
        }

        void time1_Elapsed(object sender, ElapsedEventArgs e)
        {
            time1.Enabled = false;
            try
            {
                if (wd != null && wd.Documents != null)
                {
                    Word.Application wa = this.document.Application;
                    string temp = "";
                    if (document.Content.Text != M_oldtext && M_oldtext != "")
                    {

                        object start;
                        object end;


                        if (wa.ActiveWindow.Selection.Start < 5)
                        {
                            start = 0;
                        }
                        else
                        {
                            start = wa.ActiveWindow.Selection.Start - 4;
                        }
                        end = wa.ActiveWindow.Selection.Start;
                        temp = this.document.Range(ref start, ref end).Text;





                        EventArgs_数据类 data_e = new EventArgs_数据类();
                        data_e.strTextContext = temp;
                        data_e.strTotalContext = wa.ActiveWindow.Document.Content.Text;
                        M_获取相关推送(sender, data_e);
                    }
                    else if (wa.ActiveDocument.ActiveWindow.Selection.Text != ""
                        && wa.ActiveDocument.ActiveWindow.Selection.Text != "\r"
                        && wa.ActiveDocument.ActiveWindow.Selection.Text != M_oldSelection && wa.ActiveDocument.ActiveWindow.Selection.Text.Length > 1)
                    {
                        temp = wa.ActiveDocument.ActiveWindow.Selection.Text;

                        EventArgs_数据类 data_e = new EventArgs_数据类();
                        data_e.strTextContext = temp;
                        data_e.strTotalContext = wa.ActiveWindow.Document.Content.Text;
                        M_获取相关推送(sender, data_e);

                        M_oldSelection = wa.ActiveDocument.ActiveWindow.Selection.Text;
                    }


                    M_oldtext = document.Content.Text;
                }
                time1.Enabled = true;
            }
            catch (Exception ex)
            {
                //time1.Enabled = false;
                EventArgs_数据类 data_end = new EventArgs_数据类();
                data_end.strTextContext = "#end#";
                if (M_获取相关推送 != null)
                {
                    M_获取相关推送(sender, data_end);
                }
            }
            finally
            {
                //time1.Enabled = true;
            }
            
        }

        /// <summary>
        /// 清除WordControl中所有的变量
        /// </summary>
        private void DO_ClearWordOpp()
        {
            try
            {
                this.CloseControl();
            }
            catch { }
            finally
            {
                this.document = null;
                wd = null;
                wordWnd = 0;
            }
        }

        /// <summary>
        /// 在打开WORD文档前必须执行该方法。

        /// 一般走到这个地方都是被Catch到了，是有问题的状态。pingping
        /// </summary>
        public void CloseControl()
        {

            try
            {
                object dummy = null;
                object dummy2 = (object)false;
                document.Close(ref dummy, ref dummy, ref dummy);
                wd.Quit(ref dummy2, ref dummy, ref dummy);

            }
            catch (Exception ex)
            {
                String strErr = ex.Message;
            }
        }


        public void DO_HindOpen(string ppath)
        {
            DO_ClearWordOpp();


            filename = ppath;


            if (wd == null) wd = new Word.ApplicationClass();

            if (document != null)
            {
                try
                {
                    object dummy = null;
                    wd.Documents.Close(ref dummy, ref dummy, ref dummy);
                }
                catch { }
            }

            if (wordWnd == 0) wordWnd = FindWindow("Opusapp", null);
            if (wordWnd != 0)
            {
                object fileName = filename;
                object newTemplate = false;
                object docType = 0;
                object readOnly = true;
                object isVisible = true;
                object missing = System.Reflection.Missing.Value;
                try
                {
                    if (wd == null || wd.Documents == null)
                    {
                        //throw new Exception();
                    }

                    if (wd != null && wd.Documents != null)
                    {
                        document = wd.Documents.Add(ref fileName, ref newTemplate, ref docType, ref isVisible);
                        //wd.d
                    }

                    if (document == null)
                    {
                        //throw new Exception();
                    }

                    wd.Visible = false;
                    //time1.Enabled = true;

                }
                catch
                {
                }
            }
        }
        /// <summary>
        /// 传入路径就可以直接打开word文档
        /// </summary>
        /// <param name="ppath">文档全路径</param>
        /// 
        public void DO_show(string ppath)
        {
            DO_ClearWordOpp();


            filename = ppath;


            if (wd == null) wd = new Word.ApplicationClass();

            if (document != null)
            {
                try
                {
                    object dummy = null;
                    wd.Documents.Close(ref dummy, ref dummy, ref dummy);
                }
                catch { }
            }

            if (wordWnd == 0) wordWnd = FindWindow("Opusapp", null);
            if (wordWnd != 0)
            {
                object fileName = filename;
                object newTemplate = false;
                object docType = 0;
                object readOnly = true;
                object isVisible = true;
                object missing = System.Reflection.Missing.Value;
                try
                {
                    if (wd == null || wd.Documents == null)
                    {
                        //throw new Exception();
                    }

                    if (wd != null && wd.Documents != null)
                    {
                        document = wd.Documents.Add(ref fileName, ref newTemplate, ref docType, ref isVisible);
                        //wd.d
                    }

                    if (document == null)
                    {
                        //throw new Exception();
                    }
                    
                    //wd.Visible = true;//显示word程序
                    time1.Enabled = true;

                }
                catch
                {
                }
            }
        }


        /// <summary>
        /// 传入路径就可以直接打开word文档,保存后关闭

        /// </summary>
        /// <param name="ppath">文档全路径</param>
        public void DO_CopyWord(string ppath,string psavedpath)
        {
            DO_ClearWordOpp();


            filename = ppath;


            if (wd == null) wd = new Word.ApplicationClass();

            if (document != null)
            {
                try
                {
                    object dummy = null;
                    wd.Documents.Close(ref dummy, ref dummy, ref dummy);
                }
                catch { }
            }

            if (wordWnd == 0) wordWnd = FindWindow("Opusapp", null);
            if (wordWnd != 0)
            {
                object fileName = filename;
                object newTemplate = false;
                object docType = 0;
                object readOnly = true;
                object isVisible = true;
                object missing = System.Reflection.Missing.Value;
                try
                {
                    if (wd == null || wd.Documents == null)
                    {
                        //throw new Exception();
                    }

                    if (wd != null && wd.Documents != null)
                    {
                        document = wd.Documents.Add(ref fileName, ref newTemplate, ref docType, ref isVisible);
                        //wd.d
                    }

                    if (document == null)
                    {
                        //throw new Exception();
                    }

                    //wd.Visible = true;
                    //time1.Enabled = true;
                    DO_Doc_SaveAs_HideMode(psavedpath);

                    DO_ClearWordOpp();
                }
                catch
                {
                }
            }
        }

 /// <summary>
        /// 保存当前用户受控的文档到指定路径
 /// </summary>
 /// <param name="filepath"></param>
 /// <param name="AutoRename"></param>
        public void DO_Doc_SaveAs_HideMode(string filepath)
        {
            
            if (this.document != null)
            {

                object filepa = new object();
                filepa = filepath;
                object missing = Missing.Value;
                object format = new object();
                format = 0;

                if (System.IO.File.Exists(filepath))
                {
                    FileInfo fi = new FileInfo(filepath);
                    string dir = fi.DirectoryName;
                    string file = fi.Name;
                    filepa = dir + "\\复件 " + file;
                }

                this.document.SaveAs(ref filepa, ref format, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
                //this.document.Close(ref missing, ref missing, ref missing);
            }
        }

        /// <summary>
        /// 保存当前用户受控的文档到指定路径
        /// 最后修改时间：2008.6.13 覃锋       
        /// 如果文件名字有重复，自动在文件名后加序号 
        /// </summary>
        /// <param name="filepath"></param>
        public string DO_Doc_SaveAs_HideModeEx(string filepath)
        {
            if (this.document != null)
            {

                object filepa = new object();
                filepa = filepath;
                object missing = Missing.Value;
                object format = new object();
                format = 0;

                int i = 1;
                while (System.IO.File.Exists((string)filepa))
                {
                    FileInfo fi = new FileInfo(filepath);
                    string dir = fi.DirectoryName;
                    string file = fi.Name;
                    filepa = dir + "\\" + file.Substring(0, file.IndexOf(".")) + "_" + i.ToString() + file.Substring(file.IndexOf("."), file.Length - file.IndexOf("."));
                    i++;
                }

                this.document.SaveAs(ref filepa, ref format, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
                //this.document.Close(ref missing, ref missing, ref missing);
                return (string)(filepa);
            }
            return "";
        }


        /// <summary>
        /// 打开受控文件时默认保存一次

        /// </summary>
        /// <param name="filepath"></param>
        public void DO_Doc_SaveAs_defualtMode(string filepath)
        {
            if (this.document != null)
            {

                object filepa = new object();
                filepa = filepath;
                object missing = Missing.Value;
                object format = new object();
                format = 0;

                this.document.SaveAs(ref filepa, ref format, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
                
                //退出word
                this.document.Close(ref missing, ref missing, ref missing);
                //退出app
                wd.Quit(ref missing, ref missing, ref missing);
                this.document  = null;
            }
        }
        //设置字体颜色，大小

        public void DO_insert_FontString(string value, int start, Font font)
        {
            Word.Application wa = this.document.Application;
            wa.ActiveWindow.Selection.Start = start;
            wa.ActiveWindow.Selection.End = start + value.Length;
            wa.ActiveWindow.Selection.Font.Size = font.Size;
            wa.ActiveWindow.Selection.Font.Color = font.Color;
            wa.ActiveWindow.Selection.Font.Name = font.Name;
            wa.ActiveWindow.Selection.Font.Bold = font.Bold;
            wa.ActiveWindow.Selection.Font.Italic = font.Italic;
            wa.ActiveWindow.Selection.Font.Underline = font.Underline;

        }

        //添加文字
        public bool DO_Add_String(string value)
        {
            if (this.document != null)
            {
                this.document.Content.InsertAfter(value);

                return true;
            }
            else
            {
                return false;
            }
        }

        public void DO_Insert_Table_Row(int iRowCount)
        {
            Word.Application wa = this.document.Application;
            Selection sel = wa.ActiveWindow.Selection;
            object rowCount = iRowCount;
            sel.InsertRowsAbove(ref rowCount);
            Word.Rows rows = sel.Rows;
            Word.Row row = rows.Item(1);
            
        }

        //在Word中指定表格中索引表中插入内容，如果索引不在Word中表格范围中，则在光标处插入表格
        public void DO_Add_Table(System.Data.DataTable dt,int iIndex)
        {
            try
            {
                Word.Application wa = this.document.Application;
                Selection sel = wa.ActiveWindow.Selection;
                Range range = sel.Range;

                object defaultBehaiver = WdDefaultTableBehavior.wdWord9TableBehavior;
                object autoFitBehaiver = WdAutoFitBehavior.wdAutoFitContent;
                object oMission = System.Reflection.Missing.Value;
                Word.Table table=null;;
                if (iIndex > 0 && iIndex <= wa.ActiveDocument.Tables.Count)
                {
                    table = wa.ActiveDocument.Tables.Item(iIndex);
                }
                else
                {
                    //新增表，插入表
                    table = wa.ActiveDocument.Tables.Add(range, dt.Rows.Count + 1, dt.Columns.Count, ref defaultBehaiver, ref autoFitBehaiver);
                     
                }
                if (table != null)
                {
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        try
                        {
                            table.Cell(1, i + 1).Range.Delete(ref oMission, ref oMission);
                            table.Cell(1, i + 1).Range.InsertBefore(dt.Columns[i].Caption);
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        for (int j = 0; j < dt.Columns.Count; j++)
                        {
                            try
                            {
                                table.Cell(i + 2, j + 1).Range.Delete(ref oMission, ref oMission);
                                table.Cell(i + 2, j + 1).Range.Text = dt.Rows[i].ItemArray[j].ToString();
                            }
                            catch (Exception ex)
                            {
                            }
                        }
                    }
                }

            }
            catch (Exception ex)
            {
            }
        }


        //public void DO_Add_Table(System.Windows.Forms.ListView listView)
        //{
        //    try
        //    {
        //        Word.Application wa = this.document.Application;
        //        Selection sel = wa.ActiveWindow.Selection;
        //        //Range range = (Range)sel.Rows;
        //        //Range rang = sel.Range;
        //        object start = sel.Start;
        //        Range range = this.document.Range(ref start, ref start);


        //        object defaultBehaiver = WdDefaultTableBehavior.wdWord9TableBehavior;
        //        object autoFitBehaiver = WdAutoFitBehavior.wdAutoFitContent;
        //        object oMission = System.Reflection.Missing.Value;
        //        //Word.Table table = wa.ActiveDocument.Tables.Add(range,listView.Items.Count+1,listView.Columns.Count, ref oMission,ref oMission);
        //        Word.Table table = wa.ActiveDocument.Tables.Item(1);
        //        //for (int i = 0; i < listView.Columns.Count; i++)
        //        //{
        //        //    table.Cell(1,i+1).Range.InsertBefore(listView.Columns[i].Text);
        //        //}
        //        for (int i = 0; i < listView.Items.Count; i++)
        //        {
        //            for (int j = 0; j < listView.Columns.Count; j++)
        //            {
        //                table.Cell(i+2, j + 1).Range.InsertBefore(listView.Items[i].SubItems[j].Text);
        //            }
        //        }

        //    }
        //    catch (Exception ex)
        //    {
        //    }
        //}

        public void DO_Insert_Table()
        {
            Word.Application wa = this.document.Application;

            Selection sel = wa.ActiveWindow.Selection;
            object start = sel.Start;
            Word.Range Range = this.document.Range(ref start, ref start);
            //Range = this.document.Range(ref start, ref start);
            object tableBehavior = Missing.Value; ;// "wdWord9TableBehavior";
            object autoFitBehavior = Missing.Value; ;//"wdAutoFitfixed";


            //            wa.ActiveDocument.Tables.Add(Range,10,6,ref 
            wa.ActiveDocument.Tables.Add(Range, 10, 6, ref tableBehavior, ref autoFitBehavior);
        }

        #region 写书签

        public void DO_WriteToBookMark(string BookMarkName, string BookMarkText)
        {
            try
            {

                Word.Application wa = wd.Application;
                int bookmark_cnt = this.document.Bookmarks.Count;
                int i;
                for (i = 1; i <= bookmark_cnt; i++)
                {
                    object o = (object)i;
                    if (BookMarkName.ToLower().Trim() == this.document.Bookmarks.Item(ref o).Name.ToLower().Trim())
                    {
                        this.document.Bookmarks.Item(ref o).Select();
                        wa.Selection.TypeText(BookMarkText);
                    }
                }
            }
            catch (Exception ex)
            {
                String err = ex.Message;
            }
        }
        public void DO_WriteToBookMark(WordTagMan wordTagMan)
        {
            DO_WriteToBookMark(wordTagMan.BookMarkName, wordTagMan.BookMarkText);
        }

        public void DO_WriteToBookMark(List<WordTagMan> wordTagManList)
        {
            
            try
            {
                object obj;
                //Word.Application wa = wd.Application;                 
                List<string> names = new List<string>();
                List<string> values = new List<string>();
                foreach (WordTagMan tagMan in wordTagManList)
                {   
                    obj=tagMan.BookMarkID.ToString();
                    if (obj == "tag05010108")
                    {
                        int bbb = 0;
                    }

                    if (this.document.Bookmarks.Exists(obj.ToString()))
                    {
                       // this.document.Bookmarks.Item(ref obj).Select();
                        this.document.Bookmarks.Item(ref obj).Range.Text = tagMan.BookMarkText;
                        names.Add(tagMan.BookMarkID);
                        values.Add(tagMan.BookMarkText);
                    }
                    
                
                } 
               writeXMLTest(@"c:\ttt.xml", names.ToArray(), values.ToArray());  //测试 
            }
            catch (Exception ex)
            {
                String err = ex.Message;
            }
        }
        public static void writeXMLTest(string path, string[] names, string[] values)
        {
            XmlTextWriter xmltextwrite = new XmlTextWriter(path, Encoding.UTF8);
            xmltextwrite.Formatting = Formatting.Indented;
            xmltextwrite.WriteStartDocument();// start Document 
            xmltextwrite.WriteStartElement("NewDataSet");

            xmltextwrite.WriteStartElement("测试");
            for (int i = 0; i < names.Length; i++)
            {


                xmltextwrite.WriteStartElement(names[i]);
                xmltextwrite.WriteString(values[i]);
                xmltextwrite.WriteEndElement();



            }
            xmltextwrite.WriteEndElement();

            xmltextwrite.WriteEndElement();
            xmltextwrite.WriteEndDocument();// end Document
            xmltextwrite.Flush();
            xmltextwrite.Close();

        }

        #endregion

        #region 读书签

        public string DO_ReadBookMark(string BookMarkName)
        {
            string BookMarkText = "";
            try
            {

                Word.Application wa = wd.Application;
                int bookmark_cnt = this.document.Bookmarks.Count;
                int i;
                for (i = 1; i <= bookmark_cnt; i++)
                {
                    object o = (object)i;
                    if (BookMarkName.ToLower().Trim() == this.document.Bookmarks.Item(ref o).Name.ToLower().Trim())
                    {
                        this.document.Bookmarks.Item(ref o).Select();

                        BookMarkText = wa.Selection.Text;
                    }
                }

                return BookMarkText;
            }
            catch (Exception ex)
            {
                String err = ex.Message;
                return BookMarkText;
            }
        }

        //
        public List<WordTagMan> DO_ReadAllBookMark()
        {
            List<WordTagMan> wordTagManList=new List<WordTagMan>();
            WordTagMan wordTagMan;
            try
            {

                Word.Application wa = wd.Application;
                int bookmark_cnt = this.document.Bookmarks.Count;
                int i;
                int indexNum=0;
                for (i = 1; i <= bookmark_cnt; i++)
                {
                    wordTagMan=new WordTagMan();
                    object o = (object)i;
                    wordTagMan.BookMarkID= this.document.Bookmarks.Item(ref o).Name.ToLower().Trim();
                    
                    wordTagMan.Type = wordTagMan.BookMarkID.Substring(0, 3).ToLower();
                    this.document.Bookmarks.Item(ref o).Select();
                    
                    wordTagMan.BookMarkText = wa.Selection.Text;
                    //如果书签为一般书签
                    if (wordTagMan.Type == "tag")
                    {
                        indexNum = wordTagMan.BookMarkID.IndexOf('_');
                        indexNum = indexNum < 2 ? wordTagMan.BookMarkID.Length : indexNum;
                       
                    }
                    else //否则就为其他需要处理书签
                    {
                        indexNum = wordTagMan.BookMarkID.Length;
                    
                    }
                    wordTagMan.BookMarkName = wordTagMan.BookMarkID.Substring(3, indexNum - 3);
                   
                    wordTagManList.Add(wordTagMan);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            return wordTagManList;
        }

        #endregion
    }

    public class Class_WordReader
    {
        public Class_WordReader()
        {
         }
       public Hashtable ReadDocParmars(string str_DocPath,Hashtable QueryParmarList)
       {
           Hashtable returning_hashtable = new Hashtable();
           //打开word文档
           Class_WordControler aa = new Class_WordControler();
           aa.DO_HindOpen(str_DocPath);
           foreach(string keyname in QueryParmarList.Keys)
           {
               returning_hashtable.Add(keyname, aa.DO_ReadBookMark(keyname));
           }

           aa.CloseControl();
           
           return returning_hashtable;
       }
        public string ReadFullText(string str_DocPath)
        {
            Class_WordControler aa = new Class_WordControler();
            aa.DO_HindOpen(str_DocPath);
            string fulltext = "";
            fulltext=aa.document.Content.Text;

            aa.CloseControl();
            return fulltext;
        }
    }


    public class WordTagMan
    {
        string bookMarkName;
        string bookMarkText;
        string bookMarkID;
        string type;//tag,add,..
        public string Type
        {
            get { return type; }
            set { type = value; }
        }
        public string BookMarkID
        {
            get { return bookMarkID; }
            set { bookMarkID = value; }
        }
        public string BookMarkName
        {
            get { return bookMarkName; }
            set { bookMarkName = value; }
        }
        public string BookMarkText
        {
            get { return bookMarkText; }
            set { bookMarkText = value; }
        } 
    
    }



    /// <summary>
    /// EventArgs_数据类 的摘要说明。

    /// 传输事件数据 
    /// </summary>
    /// 
    public class EventArgs_数据类 : EventArgs
    {
        public string strTextContext;
        public string strTotalContext;
    }
}
